const query=require('../db/mysql');
const { sucess,error } = require('../modle/modle');
class Cart{
    getCartList=async(ctx)=>{   //获取购物车列表
       const {userId}=ctx.query;
       //获取购物车所有userId=userId的数据
       const data=await query(`select * from cart where userId='${userId}'`)
       //遍历获取对应的商品数据
       const allp=data.map((item)=>{
           return new Promise(async(resolve,reject)=>{
               try{
                   let res=await query(`select * from shop where id='${item.shopId}'`)
                  resolve(res)
               }catch(err){
                   reject(err)
               }
           })

       })
       const shops=await Promise.all(allp)
    //    console.log(shops)
       const newDate=data.map((item,index)=>{
          return {...item,...shops[index][0]}
       })
    //    console.log(data,newDate)
       ctx.body=sucess(newDate)
    }
    addCart=async(ctx)=>{   //加入购物车
      const {userId,shopId}=ctx.request.body;
      console.log(userId,shopId)
      //判断是否已加入购物车
      const isHave=await query(`select * from cart where shopId='${shopId}' and userId='${userId}'`);
      console.log(isHave)
      let data;
      if(isHave.length){
          let sql=`update cart set count='${isHave[0].count+=1}' where shopId='${shopId}' and userId='${userId}'`
          data=await query(sql)
          ctx.body=sucess('购入车已有')
        }else{
            let sql=`insert into cart (userId,shopId,count) values ('${userId}','${shopId}','${1}')`;
            data=await query(sql)
            ctx.body=sucess('加入购入车')
        }

    }
    setCount=async(ctx)=>{
        const {id,count}=ctx.query;
        console.log()
        let sql=`update cart set count='${count}' where id='${id}'`
        const data=await query(sql)
        console.log(id,count,data)
        if(data.affectedRows===1){
            ctx.body=sucess('修改成功')
        }else{
            ctx.body=error('修改失败')
        }
    }

}

module.exports=new Cart()